package com.huixi.config.properties;

import java.io.File;
import java.net.URL;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.annotation.PostConstruct;

import com.huixi.utils.RsaUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JwtProperties {

    private String secret;

    private String pubKeyName;

    private String priKeyName;

    private int expire;

    private String cookieName;

    private Integer cookieMaxAge;

    private PublicKey publicKey;

    private PrivateKey privateKey;

    /**
     * 在构造方法之前执行该方法
     */
    @PostConstruct
    public void init() {
        try {
            URL url = JwtProperties.class.getClassLoader().getResource("rsa");
            if (url == null) {
                throw new RuntimeException("classpath下rsa目录不存在！");
            }

            String pubKeyPath = url.getPath() + "/" + pubKeyName;
            String priKeyPath = url.getPath() + "/" + priKeyName;
            File pubKey = new File(pubKeyPath);
            File priKey = new File(priKeyPath);
            //如果公钥和私钥不存在，则在classpath:rsa目录下生成
            if (!pubKey.exists() || !priKey.exists()) {
                RsaUtils.generateKey(pubKeyPath, priKeyPath, secret);
            }

            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
        } catch (Exception e) {
            log.error("初始化公钥和私钥失败！", e);
            throw new RuntimeException();
        }
    }


    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public String getPubKeyName() {
        return pubKeyName;
    }

    public void setPubKeyName(String pubKeyName) {
        this.pubKeyName = pubKeyName;
    }

    public String getPriKeyName() {
        return priKeyName;
    }

    public void setPriKeyName(String priKeyName) {
        this.priKeyName = priKeyName;
    }

    public int getExpire() {
        return expire;
    }

    public void setExpire(int expire) {
        this.expire = expire;
    }

    public String getCookieName() {
        return cookieName;
    }

    public void setCookieName(String cookieName) {
        this.cookieName = cookieName;
    }

    public Integer getCookieMaxAge() {
        return cookieMaxAge;
    }

    public void setCookieMaxAge(Integer cookieMaxAge) {
        this.cookieMaxAge = cookieMaxAge;
    }

    public PublicKey getPublicKey() {
        return publicKey;
    }

    public void setPublicKey(PublicKey publicKey) {
        this.publicKey = publicKey;
    }

    public PrivateKey getPrivateKey() {
        return privateKey;
    }

    public void setPrivateKey(PrivateKey privateKey) {
        this.privateKey = privateKey;
    }
}
